package com.heima.es;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.es.mapper.ApArticleMapper;
import com.heima.es.pojo.SearchArticleVo;
import com.heima.model.article.pojos.ApArticle;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

/**
 * @Description:
 * @Version: V1.0
 */
@SpringBootTest(classes = EsInitApplication.class)
@RunWith(SpringRunner.class)
public class InitES {

    @Autowired
    ApArticleMapper apArticleMapper;

    @Autowired
    RestHighLevelClient highLevelClient;

    /**
     * 全量导入到索引库
     *
     * 数据来源：数据库
     * 目标点： 索引库
     * 条件：已上架且未删除的所有文章数据, 分页批量导入
     *
     * 技术点：JDBC  MP  Mybatis
     * @throws Exception
     */
    @Test
    public void testInit() throws Exception{


        //1 先（条件）查询第一页数据，目的：总页数， 每一页的数据
        IPage<ApArticle> pageParam = new Page<>(1,500);
        IPage<ApArticle> pageResult = apArticleMapper.selectPage(pageParam, null);
        long totalPage = pageResult.getPages(); // 总页码 1 2 3

        //2 遍历页码，得到每一页数据 批量导入
        for (int i = 1; i <= totalPage; i++) {
            System.out.println("开始查询导入第" + i + "页数据");
            if (i > 1) {
                pageParam = new Page<>(i,500);
                pageResult = apArticleMapper.selectPage(pageParam, null);
            }

            // 每一页数据
            List<ApArticle> articleList = pageResult.getRecords();

            // 批量导入对象
            BulkRequest bulkRequest = new BulkRequest("app_info_article");

            for (ApArticle apArticle : articleList) {

                SearchArticleVo articleVo = new SearchArticleVo();
                BeanUtils.copyProperties(apArticle, articleVo);

                IndexRequest indexRequest = new IndexRequest();
                indexRequest.id(articleVo.getId().toString());
                indexRequest.source(JSON.toJSONString(articleVo), XContentType.JSON);


                bulkRequest.add(indexRequest);
            }


            // 批量导入
            BulkResponse response = highLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            System.out.println("执行结果："+response.hasFailures());
        }
    }
}
